package com.frame.auth.security.exception;

import com.frame.common.tools.result.ResultCode;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.*;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.web.HttpMediaTypeNotSupportedException;

/**
 * @auther zhangwj
 * @date 2021/3/24 下午5:11
 */
public class AuthResponseException implements WebResponseExceptionTranslator<OAuth2Exception> {

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) {
        ResultCode resultCode;
        if (e instanceof InvalidGrantException) {
            String msg = e.getMessage();
            if (null != msg && msg.contains("用户名或密码错误")) {
                resultCode = ResultCode.USERNAME_OR_PASSWORD_ERROR;
            } else {
                resultCode = ResultCode.INVALID_GRANT;
            }
        } else if (e instanceof UnsupportedGrantTypeException) {
            resultCode = ResultCode.UNSUPPORTED_GRANT_TYPE;
        } else if (e instanceof InvalidRequestException) {
            resultCode = ResultCode.INVALID_REQUEST;
        } else if (e instanceof InvalidScopeException) {
            resultCode = ResultCode.INVALID_SCOPE;
        } else if (e instanceof HttpMediaTypeNotSupportedException) {
            resultCode = ResultCode.HTTP_MEDIA_TYPE_NOT_SUPPORTED;
        } else {
            resultCode = ResultCode.ERROR;
        }
        System.out.println("统一异常:" + e);
        return new ResponseEntity<>(AuthException.getAuthException(resultCode), HttpStatus.valueOf(HttpStatus.OK.value()));
    }
}
